import { connect } from 'react-redux';
import { Form, Input, Button, Checkbox, Card } from 'antd';
import { defaultColumn } from './defaultColumn';
import { useState } from 'react';
import { useLocation } from 'umi';
import { useForm } from 'antd/lib/form/Form';

const onFinishFailed = (errorInfo) => {};

const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 8,
    span: 16,
  },
};

function Employee({ userList, dispatch }) {
  const param = useLocation().query;
  const key = param.key ? param.key : '';
  let user = {};
  const newUser = !key;
  if (key) {
    userList
      .filter((u) => {
        return u.key === key;
      })
      .forEach((u) => {
        user = {
          key: key,
          ...u,
        };
        console.log(user);
      });
  }

  const onFinish = (values) => {
    let tagsStr = values.tags;
    console.log(tagsStr);
    let tags = tagsStr.split(',');
    console.log('Success:', {
      payload: {
        ...values,
        tags: tags,
      },
    });
    if (newUser) {
      dispatch({
        type: 'create_user',
        payload: {
          user: { ...values, tags: tags },
        },
      });
    } else {
      dispatch({
        type: 'update_user',
        payload: {
          user: { ...values, tags: tags },
        },
      });
    }
  };

  return (
    <div>
      
      <Form
        {...layout}
        name="basic"
        initialValues={{
          ...user,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item key="key" label="key" name="key">
          <Input disabled={true}></Input>
        </Form.Item>
        {defaultColumn.map((m) => {
          return (
            <Form.Item
              key={m.title}
              label={m.title}
              name={m.dataIndex}
              rules={[
                {
                  required: true,
                  message: 'Please input your ' + m.title + '!',
                },
              ]}
            >
              <Input type={m.inputType}></Input>
            </Form.Item>
          );
        })}
        <Form.Item {...tailLayout}>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}

export default connect(({ userList }) => {
  return {
    userList: userList,
  };
})(Employee);
